//
//  AppDelegate+PGY.m
//  AAAAA
//
//  Created by 孙博岩 on 2018/10/14.
//  Copyright © 2018 boai. All rights reserved.
//

#import "AppDelegate+PGY.h"
#import <PgySDK/PgyManager.h>
#import <PgyUpdate/PgyUpdateManager.h>

#import "BAAlertController.h"
#import "NSObject+BAMJParse.h"
#import "BAPGYResponseModel.h"


#define KPGY_APPKEY  @"2532dda528df21afcfe71b0b8f998cf0"
#define KAPP_VERSION  @"KAPP_VERSION"

@implementation AppDelegate (PGY)
    
- (void)ba_pgy_start
{
    
    // 启动基本SDK
    [[PgyManager sharedPgyManager] startManagerWithAppId:KPGY_APPKEY];
    // 启动更新检查SDK
    [[PgyUpdateManager sharedPgyManager] startManagerWithAppId:KPGY_APPKEY];
    // 默认更新样式
//    [[PgyUpdateManager sharedPgyManager] checkUpdate];
    // 自定义更新样式
    [[PgyUpdateManager sharedPgyManager] checkUpdateWithDelegete:self selector:@selector(updateMethod:)];

    // 关闭用户反馈功能(默认开启)：
//        [[PgyManager sharedPgyManager] setEnableFeedback:NO];
    // 自定义用户反馈激活方式(默认为摇一摇)：
    // 设置用户反馈界面激活方式为三指拖动
    [[PgyManager sharedPgyManager] setFeedbackActiveType:kPGYFeedbackActiveTypeThreeFingersPan];
    
    // 设置用户反馈界面激活方式为摇一摇
    [[PgyManager sharedPgyManager] setFeedbackActiveType:kPGYFeedbackActiveTypeShake];

    // 自定义用户界面风格, 开发者可以通过设置用户反馈界面的颜色主题来改变界面风格，设置之后的颜色会影响到Title的背景颜色和录音按钮的边框颜色，默认为0x37C5A1(绿色)。
    [[PgyManager sharedPgyManager] setThemeColor:UIColor.redColor];

    // 自定义摇一摇灵敏度, 开发者可以自定义摇一摇的灵敏度，默认为2.3，数值越小灵敏度越高。
    [[PgyManager sharedPgyManager] setShakingThreshold:3.0];

    // 除了可以使用“摇一摇”和“三指拖动”来激活用户反馈，开发者还可以通过代码来直接激活用户反馈功能：
//        [[PgyManager sharedPgyManager] showFeedbackView];
    
}
    

// 版本号判断方法:
// 输出YES(服务器大与本地) 输出NO(服务器小于本地)
- (BOOL)compareEditionNumber:(NSString *)serverNumberStr localNumber:(NSString*)localNumberStr
    {
        //剔除版本号字符串中的点
        serverNumberStr = [serverNumberStr stringByReplacingOccurrencesOfString:@"." withString:@""];
        localNumberStr = [localNumberStr stringByReplacingOccurrencesOfString:@"." withString:@""];
        //计算版本号位数差
        int placeMistake = (int)(serverNumberStr.length - localNumberStr.length);
        //根据placeMistake的绝对值判断两个版本号是否位数相等
        if (abs(placeMistake) == 0)
        {
            //位数相等
            return [serverNumberStr integerValue] > [localNumberStr integerValue];
        }
        else
        {
            //位数不等
            //multipleMistake差的倍数
            NSInteger multipleMistake = pow(10, abs(placeMistake));
            NSInteger server = [serverNumberStr integerValue];
            NSInteger local = [localNumberStr integerValue];
            if (server > local)
            {
                return server > local * multipleMistake;
            }
            else
            {
                return server * multipleMistake > local;
            }
        }
    }

- (void)updateMethod:(NSDictionary *)response
{
    BAPGYResponseModelData *model = [BAPGYResponseModelData ba_MJParse:response];
    NSLog(@"更新更新内容：：：%@", model.releaseNote);

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    //当前版本号
    NSString *currentVersion = infoDictionary[@"CFBundleShortVersionString"];
    NSString *app_Name = infoDictionary[@"CFBundleDisplayName"];
    app_Name = app_Name.length ? app_Name:infoDictionary[@"CFBundleName"];
    NSString *oldVersion = [[NSUserDefaults standardUserDefaults] objectForKey:KAPP_VERSION];
    if (!oldVersion.length)
    {
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:KAPP_VERSION];;
    }
    else
    {
        if ([model.haveNewVersion boolValue])
        {
            bool isNewVersion = [self compareEditionNumber:currentVersion localNumber:oldVersion];
            
            NSString *title = [NSString stringWithFormat:@"%@ 发现新版本啦！！！", app_Name];
            NSString *msg = [NSString stringWithFormat:@"\n当前版本：%@\n上次版本：%@\n更新内容：%@\n是否有更新：%@", currentVersion, oldVersion, model.releaseNote, isNewVersion?@"YES":@"NO"];
            NSLog(@"%@\n%@", title, msg);
            
            [UIAlertController ba_alertShowInViewController:[UIApplication sharedApplication].keyWindow.rootViewController title:title message:msg buttonTitleArray:@[@"sure"] buttonTitleColorArray:@[UIColor.redColor] block:^(UIAlertController * _Nonnull alertController, UIAlertAction * _Nonnull action, NSInteger buttonIndex) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:model.downloadURL] options:nil completionHandler:^(BOOL success) {
                    if (!success)
                    {
                        [self exitApplication];
                    }
                }];
            }];
        }
    }
}

- (void)exitApplication
{
    AppDelegate *app = [UIApplication sharedApplication].delegate;
    UIWindow *window = app.window;
    
    [UIView animateWithDuration:1.0f animations:^{
        window.alpha = 0;
        window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
    } completion:^(BOOL finished) {
        exit(0);
    }];
    //exit(0);
}

@end
